package top.longmarch.flow.component;

import com.yomahub.liteflow.core.NodeComponent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import top.longmarch.flow.dto.LiteFlowDTO;
import top.longmarch.flow.entity.LiteflowChain;
import top.longmarch.flow.service.ILiteflowChainService;
import top.longmarch.flow.slot.LiteflowChainContext;
import top.longmarch.parser.node.ELBusPlus;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

@Slf4j
@Component("saveFlowChainCmp")
public class SaveFlowChainCmp extends NodeComponent {

    @Resource
    private ILiteflowChainService liteflowChainService;

    @Override
    public void process() throws Exception {
        LiteFlowDTO req = this.getRequestData();
        LiteflowChainContext context = this.getContextBean(LiteflowChainContext.class);
        LiteflowChain liteflowChain;
        if (Objects.nonNull(req.getId())) {
            liteflowChain = liteflowChainService.getById(req.getId());
            if (Objects.isNull(liteflowChain)) {
                throw new RuntimeException("流程不存在");
            }
            if (!liteflowChain.getModifyPermissions()) {
                throw new RuntimeException("无修改权限");
            }
        } else {
            liteflowChain = new LiteflowChain();
        }
        liteflowChain.setId(req.getId());
        liteflowChain.setApplicationName(req.getApplicationName());
        liteflowChain.setChainName(req.getChainName());
        liteflowChain.setChainDesc(req.getChainDesc());
        liteflowChain.setJsonData(req.getJsonData());
        liteflowChain.setElData(ELBusPlus.toEl(liteflowChain.getJsonData()));
        liteflowChain.setEnable(req.getEnable());
        liteflowChain.setCreateTime(new Date());
        if (liteflowChainService.saveOrUpdate(liteflowChain)) {
            context.setLiteflowChain(liteflowChain);
        }
    }

}
